package net.appositedesigns.appshare;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.ProgressDialog;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.widget.TextView;

public class AppFinder extends AsyncTask<String, Integer, List<AppListEntry>> {

	private AppList mContext;
	private ProgressDialog waitDialog;
	
	public AppFinder(AppList mContext) {
		this.mContext = mContext;
	}
	@Override
	protected void onPostExecute(final List<AppListEntry> result) {

		mContext.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				
				TextView emptyText = (TextView)mContext.getListView().getEmptyView();
				emptyText.setText("No apps installed");

				mContext.setApps(result);
				if(waitDialog!=null && waitDialog.isShowing())
				{
					waitDialog.dismiss();
				}
			}
		});

	}
	@Override
	protected List<AppListEntry> doInBackground(String... arg0) {
		
		String query = null;
		if(arg0.length>0)
		{
			mContext.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
			    	waitDialog = ProgressDialog.show(mContext, "", 
			                mContext.getString(R.string.searching_apps), true);					
				}
			});

			query = arg0[0];
		}
		else
		{
			mContext.runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
			    	waitDialog = ProgressDialog.show(mContext, "", 
			                mContext.getString(R.string.fetching_apps), true);					
				}
			});
		}
		List<PackageInfo> packages = mContext.getPackageManager().getInstalledPackages(PackageManager.GET_META_DATA);
        final List<AppListEntry> installed = new ArrayList<AppListEntry>();
        
        for(PackageInfo p :packages)
        {
        	if((p.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM)==0)
        	{
        		CharSequence appName = p.applicationInfo.loadLabel(mContext.getPackageManager());
        		if(query==null || query.toLowerCase().contains(appName.toString().toLowerCase()))
        		{
	        		AppListEntry app = new AppListEntry();
	        		app.setAppName(appName);
	        		app.setAppIcon(p.applicationInfo.loadIcon(mContext.getPackageManager()));
	        		app.setPackageName(p.applicationInfo.packageName);
	        		installed.add(app);
        		}
        	}
        }
        
        Comparator<AppListEntry> comp = new Comparator<AppListEntry>() {
			
			@Override
			public int compare(AppListEntry p1, AppListEntry p2) {
				
				CharSequence label1 = p1.getAppName();
				CharSequence label2 = p2.getAppName();
				
				return label1.toString().compareTo(label2.toString());
				
			}
		};
		
		Collections.sort(installed, comp);

		return installed;
	}
	
}
